import uniCrazyRouter from "uni-crazy-router";
import Vue from "vue";

Vue.use(uniCrazyRouter);

const wildcardToRegular = (str) => {
  str = str.replace(/[[\]\\^:.?+]/g, (m) => `\\${m}`);
  str = str.replace(/\*\*|\*/g, (m) => (m == "**" ? "[\\w\\W]*" : "[^\\/]*"));
  return new RegExp(str, "gi");
};

const isPathMatch = (path, wildcard) => {
  if (Array.isArray(wildcard)) {
    for (let i = 0; i < wildcard.length; i++) {
      if (wildcardToRegular(wildcard[i]).test(path)) {
        return true;
      }
    }
    return false;
  }
  return wildcardToRegular(wildcard).test(path);
};

const blackList = [
  /* "pages-member/afterSale**",
     "pages-customer/customer**",
     "pages-member/financial**",
     "pages-member/order**",
     "pages-member/payRecord**",
     "pages-member/points**",
     "pages-member/procurement**",
     "pages-member/quote**",
     "pages-member/relationMember**",
     "pages-member/share**",
     "pages-member/updatePassword**",
     "pages-member/user**",
     "pages-customer/customer**",
     "pages-mall/goods/addressAdd",
     "pages-mall/goods/addressList",
     "pages-mall/goods/customerAdd",
     "pages-mall/goods/customerList",
     "pages-mall/point/task",
     "pages-mall/point/submit",
     "pages-mall/point/pointDetail",
     "pages-mall/flashSale/order",
     "pages/index/cart" */
];

const whiteList = ["pages-member/procurement/list"];

uniCrazyRouter.beforeEach(async (to, from, next) => {
  // 逻辑代码
  const token = uni.getStorageSync("yl-token");
  const o = isPathMatch(to.url, blackList); // 需要登录验证
  if (o && !isPathMatch(to.url, whiteList)) {
    if (!token) {
      console.log("因为未登录，拦截去登录页面");
      uniCrazyRouter.afterNotNext(() => {
        uni.reLaunch({
          url: `/pages-user/login/login?to=/${to.url}&from=/${from.url}`
        });
      });
    } else {
      /* if (to.url == "pages-customer/customer/enterprise") {
              let hasInfo = "";
              await api.getInFo().then(res => {
                if (res.data && res.data.companyId) {
                  hasInfo = true;
                } else {
                  hasInfo = false;
                }
              });
              if (hasInfo) {
                console.log("hasInfo", hasInfo);
                uniCrazyRouter.afterNotNext(() => {
                  uni.navigateTo({ url: "/pages-customer/customer/enterprise2" });
                });
              } else {
                next();
              }
              return;
            } else {
              next();
            } */
      next();
    }
  } else {
    next();
  }
});
